clear
set more			 off
cap   log close 		_all
use "$datapath/A3_age55data_WC_rdrobust.dta",clear



{ // Generate: Event time to displacement
*===============================================================================
bys lopnr (date) : gen lastmonthwork =  date if  atfirm2[_n-1]==1 & atfirm2==1 & atfirm2[_n+1]==0  & atfirm2[_n+2]==0 
format lastmonthwork %tm

bys lopnr (date) : gen SPnvals = sum(1) 	if lastmonthwork!=.
tab SPnvals 				if lastmonthwork!=.
bys lopnr : egen maxnvals = max(SPnvals)

*Take away displacemnt dates that occur 12 months before notification for those with multiple displacments dates
replace lastmonthwork=. if eventtime_def<-12 & maxnvals>1


bys lopnr (date) : gen SPnvals2 = sum(1) 	if lastmonthwork!=.
tab SPnvals2 				if lastmonthwork!=.
bys lopnr : egen maxnvals2 = max(SPnvals2)
*Now 93.87 percent are displaced only once

 gen SPdiff = lastmonthwork - notdate_def
 tab SPdiff treat 
*So very few do not work 12 months prior to notification so we get rid of these
replace lastmonthwork=. if eventtime_def<-12
drop SPdiff

   
*Taking the minimum date assures that we get the nvals==1 as displacement date
fastmin lastmonthwork , by(lopnr) name(dispdate)
replace dispdate = dispdate +1
format dispdate %tm

*Recalls (working 3 months after displacement event has occured)
bys lopnr (date) : gen xrecalldate = date if atfirm2[_n-2]==0 & atfirm2[_n-1]==0 & atfirm2==1 & atfirm2[_n+1]==1 & atfirm2[_n+3]==1 & date>dispdate
fastmin xrecalldate , by(lopnr) name(recalldate)
format recalldate %tm
drop x*
gen recalled = recalldate!=.   
   
*Generate: Month of displacement
gen monthofdisp = month(dofm(dispdate))

*Generate: Months worked after notification
gen RAMSmonths = dispdate - notdate_def

*Generate: Displacement event time
bys lopnr (date) : gen dispeventtime = date - dispdate

*Generate: Months working at notifying firm in a year
bys lopnr year (date) : egen monthsatfirm = total(atfirm2)

* SP5 preffered metric for SP!!!
bys lopnr (date) : gen SP3 = (annual_ear_atfirm - (annual_ear_atfirm[_n-12]/monthsatfirm[_n-12])*monthofdisp) if dispeventtime==0
bys lopnr (date) : gen SP4 = (annual_ear_atfirm + annual_ear_atfirm[_n+12] - (annual_ear_atfirm[_n-12]/monthsatfirm[_n-12])*monthofdisp) if dispeventtime==0
bys lopnr (date) : gen SP5 = SP3 
bys lopnr (date) : replace SP5 = SP5 + annual_ear_atfirm[_n+12] if monthsatfirm[_n+12]==1
gen posSP = SP3>0
*bys lopnr (date) : gen SP5 = ( (annual_ear_atfirm/monthofdisp - (annual_ear_atfirm[_n-12]/monthsatfirm[_n-12]))*monthofdisp if dispeventtime==0

drop SPnvals*
}
*


*keep relevant variables and eventtime
keep dispeventtime SP5 lopnr year firmid
keep if dispeventtime==0

*Winsorize
winsor2 SP5, c(1 99) suffix(_win_1_99)
winsor2 SP5, c(5 95) suffix(_win_5_95)
winsor2 SP5, c(1 99) suffix(_win_1_99_byyear) by(year)
winsor2 SP5, c(5 95) suffix(_win_5_95_byyear) by(year)
rename SP5 SP5_large

*Save data
compress
save "$datapath/SP.dta",replace
